Imports org.model.lib.db

''' <summary>
''' CFA: Country Code/Period Code/Student Counter
''' </summary>
''' <remarks></remarks>
Class CFACandidateCodeGenerator
    Inherits ICandidateCodeGenerator


    Public Overrides Function getStudentCounter() As Integer
        Dim sql = <sql>
SELECT  max(convert(int,SUBSTRING(a.CandidateCode, 10, 4)) ) AS num
FROM    ClassMember AS a INNER JOIN
        Class AS b ON a.ClassId = b.ClassId INNER JOIN
        Period AS c ON b.PeriodId = c.PeriodId
WHERE   c.DiplomaSuperTypeId=4
order by 1 desc
</sql>

        Dim ret As Integer = ModelContext.CurrentDBUtils.getLngValueWithParams(sql.Value)
        ret = ret + 1

        Return ret

    End Function

    Public Overrides Function getExistingCandidateCode() As String

        Dim oldrecords As List(Of ClassMember) = ClassMemberDataUtils.findList("studentId={0}", _
                                     Me.student.StudentId)

        For Each cm As ClassMember In oldrecords
            If cm.PeriodClass.Period.DiplomaSuperTypeId = EnumDiplomaSuperTypes.CFA Then
                Return cm.CandidateCode
            End If
        Next
        Return String.Empty

    End Function

    Public Overrides Function getNewCandidateCode() As String

        If Me.periodClass.ExamCenter Is Nothing OrElse _
                Me.periodClass.ExamCenter.CountryId.GetValueOrDefault = 0 Then

            Throw New ApplicationException("You must select an exam center before adding students to the Exam session")

        End If

        'Candidate code:  Country Code/Period Code/Student Counter for Country Code
        Dim candCode As String = Me.periodClass.ExamCenter.Country.CountryCode & "/" & _
                                Me.periodClass.Period.PeriodCode & "/"

        Dim stCounter As Integer = Me.getStudentCounter

        candCode = candCode & Format(stCounter, "0000")
        Return candCode
    End Function
End Class
